# !usr/bin/env python
# -*- coding:utf-8 _*-


import os
from time import strftime
import logging


def log(log_file=None):
    def make_log_file(file):
        if file is None:
            file = os.path.join(os.getcwd(), 'log', 'Log_' + strftime('%Y_%m_%d_%H_%M_%S') + '.log')
        log_path = os.path.dirname(file)
        if not os.path.exists(log_path):
            os.makedirs(log_path)
        return file

    # 创建一个logger
    logger = logging.getLogger()
    # Log等级总开关,低于此级别的都不会记录
    logger.setLevel(logging.DEBUG)
    # 自定义log目录
    log_file = make_log_file(log_file)
    # 创建一个handler，用于写入日志文件
    filehandler = logging.FileHandler(filename=log_file, encoding='utf-8')
    # 用于写到file的等级开关
    filehandler.setLevel(logging.DEBUG)
    # 再创建一个handler,用于输出到控制台
    consolehandler = logging.StreamHandler()
    # 输出到console的log等级的开关
    consolehandler.setLevel(logging.ERROR)  # logging.INFO  ERROR
    # 定义handler的输出格式
    fileformatter = logging.Formatter('%(asctime)s - %(filename)20s[line:%(lineno)5d] - %(levelname)s: %(message)s')
    consoleformatter = logging.Formatter('%(asctime)s - %(levelname)s: %(message)s')
    filehandler.setFormatter(fileformatter)
    # consolehandler.setFormatter(consoleformatter)
    consolehandler.setFormatter(fileformatter)
    # 将logger添加到handler里面
    logger.addHandler(filehandler)
    logger.addHandler(consolehandler)
    # logger.info(f"Log file: {log_file}")
    return logger


try:
    LOG
except NameError:
    LOG = log()
